#include "common.h"
#include "syntax-tree.h"

static const size_t len=sizeof(tree_node);

void treeNodeCheck(const tree_node * x){
    Assert(x,"Unexpected NULL tree_node!");
    Assert(x->ch_num>=0&&x->ch_num<=7,"Unexpected child num %d!",x->ch_num);
    for(int i=0;i<x->ch_num;i++) 
    Assert(x->ch[i],"Should have son %d with total son %d!",i,x->ch_num);
    for(int i=x->ch_num;i<7;i++) 
    Assert(x->ch[i]==NULL,"Unexpected son %p at %d with total son %d!",x->ch[i],i,x->ch_num);
}

tree_node * treeNodeInit(int id,int first_line,int rule){
    tree_node * x=malloc(len);
    memset(x,0,len);
    x->type=id;x->info="";x->first_line=first_line;x->rule=rule;
    return x;
}

void treeNodeInsert(tree_node * x,tree_node * y){
    treeNodeCheck(x);treeNodeCheck(y);
    x->ch[x->ch_num++]=y;
    x->not_null|=y->not_null;
}

void treeNodeDFS(const tree_node * now,void (*func)(const tree_node *a)){
    treeNodeCheck(now);
    for(int i=0;i<now->ch_num;i++) if(now->ch[i]->not_null)
        treeNodeDFS(now->ch[i],func);
    func(now);
}

tree_node * treeNodeTokenInit(int id,int first_line){
    tree_node * x=malloc(len);
    memset(x,0,len);
    x->type=id;x->info="";x->not_null=1;x->first_line=first_line;
    return x;
}
